package com.maizhi.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.maizhi.dao.BaseDaoI;
import com.maizhi.model.Resource;
import com.maizhi.model.Role;
import com.maizhi.model.RoleResource;
import com.maizhi.model.User;
import com.maizhi.model.UserRole;
import com.maizhi.service.AuthServiceI;

/**
 * 权限Service
 * 
 */
@Service("authService")
public class AuthServiceImpl extends BaseServiceImpl implements AuthServiceI {

	private BaseDaoI<Resource> resourceDao;
	private BaseDaoI<User> userDao;

	public BaseDaoI<Resource> getResourceDao() {
		return resourceDao;
	}

	@Autowired
	public void setResourceDao(BaseDaoI<Resource> resourceDao) {
		this.resourceDao = resourceDao;
	}

	public BaseDaoI<User> getUserDao() {
		return userDao;
	}

	@Autowired
	public void setUserDao(BaseDaoI<User> userDao) {
		this.userDao = userDao;
	}

	@Cacheable(value = "AuthCache", key = "'offResourcesList'")
	@Transactional(readOnly = true)
	public List<Resource> offResourcesList() {
		return resourceDao.find("from Resource t where t.onoff != '1'");
	}
	
	@Cacheable(value = "AuthCache", key = "'offLoginList'")
	@Transactional(readOnly = true)
	public List<Resource> offLoginList() {
		return resourceDao.find("from Resource t where t.isLogin != '1'");
	}

	@Cacheable(value = "AuthCache", key = "'getResourcesByRequestPath'+#requestPath")
	@Transactional(readOnly = true)
	public Resource getResourcesByRequestPath(String requestPath) {
		return resourceDao.get("from Resource t where t.src=?", requestPath);
	}

	@Cacheable(value = "AuthCache", key = "'checkAuth'+#userId+#requestPath")
	@Transactional(readOnly = true)
	public boolean checkAuth(String userId, String requestPath) {
		boolean b = false;
		User u = userDao.get(User.class, userId);
		Set<UserRole> ur = u.getRoles();// 用户和角色关系
		for (UserRole ul : ur) {
			Role r = ul.getRole();
			Set<RoleResource> rs = r.getRoleResources();// 角色和资源关系
			for (RoleResource roleResources : rs) {
				Resource res = roleResources.getResource();
				if (res.getSrc() != null && requestPath.equals(res.getSrc())) {
					return true;
				}
			}
		}
		return b;
	}

	

}
